package mail

import (
	"net"
	"strings"
)

func HandleConnection(conn net.Conn) {
	defer conn.Close()
	conn.Write([]byte("220 localhost SMTP server ready\\r\\n"))
	buf := make([]byte, 1024)
	for {
		n, err := conn.Read(buf)
		if err != nil {
			break
		}
		cmd := strings.TrimSpace(string(buf[:n]))
		switch {
		case strings.HasPrefix(cmd, "HELO") || strings.HasPrefix(cmd, "EHLO"):
			conn.Write([]byte("250 Hello\r\n"))
		case strings.HasPrefix(cmd, "MAIL FROM"):
			conn.Write([]byte("250 OK\r\n"))
		case strings.HasPrefix(cmd, "RCPT TO"):
			conn.Write([]byte("250 OK\r\n"))
		case strings.HasPrefix(cmd, "DATA"):
			conn.Write([]byte("354 Start mail input; end with <CRLF>.<CRLF>\\r\\n"))
		case cmd == ".":
			conn.Write([]byte("250 OK: Message accepted\\r\\n"))
		case strings.HasPrefix(cmd, "QUIT"):
			conn.Write([]byte("221 Bye\r\n"))
			return
		default:
			conn.Write([]byte("500 Command not recognized\r\n"))
		}
	}
}
